import 'dart:io';

import 'package:electronic_pet/pages/desktop_popup/desktop_popup.dart';
import 'package:flutter/material.dart';
import 'package:leancloud_storage/leancloud.dart';
import 'package:window_manager/window_manager.dart';

class LoginView extends StatefulWidget {
  const LoginView({super.key});

  @override
  State<StatefulWidget> createState() => _LoginView();
}

class _LoginView extends State<LoginView> {
  @override
  void initState() {
    super.initState();
    loginBySession();
    WidgetsBinding.instance.addPostFrameCallback((_) => windowResize());
  }

  windowResize() async {
    Size size = const Size(500, 600);
    await windowManager.setSize(size, animate: false);
  }

  loginBySession() async {
    final file = File('sessionToken.txt');
    // 如果session文件不存在
    if (!await file.exists()) {
      return;
    }
    String sessionToken = await file.readAsString();
    if (sessionToken.isNotEmpty) {
      // 使用session登录
      LCUser.becomeWithSessionToken(sessionToken);
      LCUser? currentUser = await LCUser.getCurrent();
      bool? isAuthenticated = await currentUser?.isAuthenticated();
      if (isAuthenticated == true) {
        Navigator.of(context).pushReplacement(
            MaterialPageRoute(builder: (context) => const DesktopPopupPage()));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    TextEditingController userNameController = TextEditingController();
    TextEditingController passwordController = TextEditingController();
    buttonPressed() async {
      var userName = userNameController.text;
      var password = passwordController.text;
      if (userName.isEmpty || password.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text('用户名或密码不能为空'), backgroundColor: Colors.red));
        return false;
      }
      try {
        //使用密码登陆
        LCUser user = await LCUser.login(userName, password);
        // Store the session token locally
        final file = File('sessionToken.txt');
        await file.writeAsString(user.sessionToken ?? "");
      } on LCException {
        // 登录失败（可能是密码错误）
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text('用户名或者密码错误'), backgroundColor: Colors.red));
        return false;
      }

      Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => const DesktopPopupPage()));
    }

    return Scaffold(
        appBar: AppBar(
          title: const Text('登陆'),
          centerTitle: true,
        ),
        body: Padding(
            padding: const EdgeInsets.only(top: 20.0), // 设置顶部间距为 20 像素

            child: Column(
              children: [
                TextField(
                    decoration: InputDecoration(
                      labelText: "用户名",
                      hintText: "请输入用户名",
                      prefixIcon: const Icon(Icons.person),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide:
                            const BorderSide(color: Colors.black12, width: 2),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide:
                            const BorderSide(color: Colors.orange, width: 2),
                      ),
                    ),
                    controller: userNameController),
                const SizedBox(height: 30), // 添加这一行
                TextField(
                  decoration: InputDecoration(
                    labelText: "密码",
                    hintText: "请输入密码",
                    prefixIcon: const Icon(Icons.lock),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide:
                          const BorderSide(color: Colors.black12, width: 2),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide:
                          const BorderSide(color: Colors.orange, width: 2),
                    ),
                  ),
                  obscureText: true,
                  controller: passwordController,
                ),
                ElevatedButton(
                    onPressed: () {
                      buttonPressed();
                    },
                    child: const Text("登陆")),
                const Text("忘记密码? | 注册账号"),
              ],
            )));
  }
}
